<template>
  <div class="my-process-veiwer">
    <div ref="bpmn-canvas" class="process-veiwer-container"></div>
  </div>
</template>

<script>
import BpmnViewer from "bpmn-js/lib/Viewer";
export default {
  name: "MyProcessVeiwer",
  componentName: "MyProcessVeiwer",
  props: {
    value: {
      type: String,
      default: ""
    },
    lineData: {
      type: Array,
      default: () => []
    }
  },
  mounted() {
    this.initBpmnViewer();
    this.createNewDiagram(this.value);
    this.$once("hook:beforeDestroy", () => {
      if (this.BpmnViewer) this.BpmnViewer.destroy();
      this.$emit("destroy", this.BpmnViewer);
      this.BpmnViewer = null;
    });
  },

  watch: {
    value() {
      this.createNewDiagram(this.value);
    },
    lineData() {
      this.createNewDiagram(this.value);
    }
  },
  methods: {
    initBpmnViewer() {
      //初始化module
      if (this.BpmnViewer) return;
      this.BpmnViewer = new BpmnViewer({
        container: this.$refs["bpmn-canvas"]
      });
      this.elementRegistry = this.BpmnViewer.get("elementRegistry");
      this.graphicsFactory = this.BpmnViewer.get("graphicsFactory");
    },
    async createNewDiagram(value) {
      //绘制
      if (!value) return "需要传入XML哦~!";
      console.log("开始绘制");
      await this.BpmnViewer.importXML(value);
      this.setByColor(this.lineData);
      this.BpmnViewer.get("canvas").zoom("fit-viewport");
    },
    setByColor(data) {
      if (!data.length) return "没有数据哦~!";
      console.log("开始遍历颜色", data);
      data.map(item => {
        const { name, stroke, fill } = item;
        const element = this.elementRegistry.get(name);
        this.setColor(element, stroke, fill);
      });
    },
    setColor(element, stroke, fill) {
      console.log("开始设置颜色函数", element.id, stroke, fill);
      const businessObject = element.businessObject;
      businessObject.di.set("stroke", stroke);
      businessObject.di.set("fill", fill);
      const gfx = this.elementRegistry.getGraphics(element);
      const type = element.waypoints ? "connection" : "shape";
      this.graphicsFactory.update(type, element, gfx);
    }
  }
};
</script>
